import Taro from '@tarojs/taro'

import {getJSON, postJSON} from '../utils'
import apiObj from '../api'
import {GET_USER_TOKEN, GEt_USER_TOKEN_FAIL} from '../constants/user'

/**
 * action creator
 */
export const userAccessToen = (params, data) => {
  return {
    type: GET_USER_TOKEN,
    accesstoken: params.accesstoken,
    loginname: data.loginname,
    avatar_url: data.avatar_url
  }
}

export const userAccessTokenFail = () => {
  return {
    type: GEt_USER_TOKEN_FAIL,
    accesstoken: null,
    loginname: null
  }
}

/**
 * dispatch action
 * @param {*} params 
 */
export function userAccessTokenAction(params){
  return async dispatch => {
    let result = await postJSON(apiObj.checkUser, params)
    if(result && result.data && result.data.success){
      let data = result.data
      dispatch(userAccessToen(params, data))
      // return result.data
    }else{
      dispatch(userAccessTokenFail())
    }
    return false
  }
}

export async function getUserInfo(params){
  console.log(params)
  let result = await getJSON(apiObj.getUserInfo + params.loginname, params)
  if(result && result.data && result.data.success){
    return result.data
  }else{
    Taro.showToast({title: '获取用户信息失败', icon: 'none'})
  }
}

export async function checkUserLoginStatus(params){
  if(params && params.accesstoken){
    return true
  }
  return false
}